package com.server.questionbank.snframe.service.HomeworkService.Impl;

import com.server.questionbank.snframe.domain.Course.Member.CusStudyGroup;
import com.server.questionbank.snframe.domain.Course.Member.UserRegistCus;
import com.server.questionbank.snframe.domain.Homework.*;
import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.mapper.Homework.HomeworkMapper;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberGroupService;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberService;
import com.server.questionbank.snframe.service.CourseService.TExerciseService;
import com.server.questionbank.snframe.service.HomeworkService.HomeworkService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class HomeworkServiceImpl implements HomeworkService {
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private UsersService usersService;
    @Autowired
    private CusMemberGroupService cusMemberGroupService;
    @Autowired
    private CusMemberService cusMemberService;
    @Autowired
    private TExerciseService tExerciseService;

    // 获取作业列表
    @Override
    public List<THomework> getHomeworkList(Long targetId, String homeworkType) {
        if (targetId == null) return null;
        List<THomework>  homework = homeworkMapper.getHomeworkListFlexible(targetId, homeworkType);
        if(homework != null) return homework.stream().map(homeworkInfo -> {
            homeworkInfo.setExercises(getHomeworkExercises(homeworkInfo.getHomeworkId()));
            return homeworkInfo;
        }).collect(Collectors.toList());
        return null;
    }

    // 获取作业发布列表
    @Override
    public List<HomeworkPublish> getPublishHomeworkList(Long targetId, String homeworkType) {
        if (targetId == null) return null;
        TUser user = usersService.getLoginUser();
        if (user == null) { return null; }
        Long groupId = null;
        // 获取当前登录用户在课程中的成员消息
        UserRegistCus  cusMemberInfo = cusMemberService.getMemberInfo(targetId, user.getUserId());
        // 获取当前登录用户所在分组
        if (cusMemberInfo != null) groupId = cusMemberInfo.getGroupId();
        // 获取作业发布信息
        List<HomeworkPublish> homeworkPublishList = homeworkMapper.getHomeworkPublishListFlexible(targetId, groupId, homeworkType);
        pushHomeworkPublish(homeworkPublishList);
        return homeworkPublishList;
    }

    // 获取指定作业的作业发布信息
    @Override
    public List<HomeworkPublish> getPublishHomeworkByHomeworkId(Long homeworkId) {
        List<HomeworkPublish> homeworkPublishList = homeworkMapper.getPublishHomeworkByHomeworkId(homeworkId);
        pushHomeworkPublish(homeworkPublishList);
        return homeworkPublishList;
    }

    // 获取发布作业
    @Override
    public HomeworkPublish getHomeworkPublishById(Long publishId) {
        if (publishId == null) return null;
        HomeworkPublish  homeworkPublish = homeworkMapper.getHomeworkPublishById(publishId);
        if (homeworkPublish == null) return null;
        List<HomeworkPublish> homeworkPublishList = new ArrayList<>();
        homeworkPublishList.add(homeworkMapper.getHomeworkPublishById(publishId));
        pushHomeworkPublish(homeworkPublishList);
        return homeworkPublishList.get(0);
    }

    // 填充作业成员信息
    private void pushHomeworkPublish(List<HomeworkPublish> homeworkPublishList) {
        TUser user = usersService.getLoginUser();
        // 获取作业信息
        homeworkPublishList.stream().map(homeworkPublish -> {
            // 获取作业发布目标
            homeworkPublish.setCusStudyGroup(cusMemberGroupService.getCusStudyGroupById(homeworkPublish.getTargetId()));

            THomework homeworkInfo = homeworkMapper.getHomeworkById(homeworkPublish.getHomeworkId());
            if(homeworkInfo != null)
            {
                homeworkInfo.setExercises(getHomeworkExercises(homeworkInfo.getHomeworkId()));
                if (homeworkInfo.getExercises() != null) homeworkInfo.setExerciseCount(homeworkInfo.getExercises().size());
                // 获取作业信息
                homeworkPublish.setHomeworkInfo(homeworkInfo);
            }

            // 获取当前登录用户答题记录
            UreceiveHwrec ureceiveHwrec = null;
            if (user != null) ureceiveHwrec = homeworkMapper.getUserAnswerRecord(user.getUserId(), homeworkPublish.getPublishId());
            Integer status;
            Float score = 0f;
            if (ureceiveHwrec == null) status = 0; // 未提交
            else if (ureceiveHwrec.getMarkTime() == null) status = 1; // 待批改
            else if (ureceiveHwrec.getMarkMan() == null || ureceiveHwrec.getMarkMan().isEmpty()) status = 2; // 有批阅时间但是没有批阅人，则为AI代批阅
            else status = 3; // 已批改
            if ((status == 2 || status == 3) && ureceiveHwrec.getScore() != null) score = ureceiveHwrec.getScore();

            // 获取作业所有成员答题状况
            // 获取所有成员
            List<UserRegistCus> userRegistCusList = cusMemberService.getAllMember(homeworkPublish.getHomeworkInfo().getTargetId(), homeworkPublish.getTargetId());
            AtomicReference<Integer> submitCount = new AtomicReference<>(0);
            AtomicReference<Integer> unSubmitCount = new AtomicReference<>(0);
            AtomicReference<Integer> pendingReviewCount = new AtomicReference<>(0);
            // 遍历成员列表，统计提交、未提交和待审核的个数
            homeworkPublish.setHomeworkMembers(userRegistCusList.stream().map(userRegistCus -> {
                HomeworkMember homeworkMember = new HomeworkMember();
                homeworkMember.setCourseMember(userRegistCus);
                UreceiveHwrec courseMemberUreceiveHwrec =
                        homeworkMapper.getUserAnswerRecord(userRegistCus.getUserId(), homeworkPublish.getPublishId());
                if (courseMemberUreceiveHwrec == null) unSubmitCount.getAndSet(unSubmitCount.get() + 1);
                else if (courseMemberUreceiveHwrec.getMarkTime() == null) pendingReviewCount.getAndSet(pendingReviewCount.get() + 1);
                else submitCount.getAndSet(submitCount.get() + 1);
                homeworkMember.setUreceiveHwrec(courseMemberUreceiveHwrec);
                return homeworkMember;
            }).collect(Collectors.toList()));
            homeworkPublish.setSubmitCount(submitCount.get());
            homeworkPublish.setUnSubmitCount(unSubmitCount.get());
            homeworkPublish.setPendingReviewCount(pendingReviewCount.get());
            homeworkPublish.setStatus(status);
            homeworkPublish.setScore(score);
            return homeworkPublish;
        }).collect(Collectors.toList());
    }

    // 设置作业
    @Override
    public Boolean setHomework(THomework homework) {
        boolean create = false;
        if (homework.getHomeworkId() == null || homework.getHomeworkId() <= 0) return createHomework(homework);
        else if (homeworkMapper.getHomeworkById(homework.getHomeworkId()) == null) return createHomework(homework);
        else return updateHomework(homework);
    }

    // 设置作业题目
    @Override
    public Boolean updateHomeworkExercises(List<HomeworkExercises> homeworkExercises) {
        if (homeworkExercises != null) {
            // 删除作业所有题目
            homeworkMapper.deleteHomeworkExercises(homeworkExercises.get(0).getHomeworkId());
            // 添加作业题目
            return homeworkExercises.stream().map(homeworkExercise -> {
                homeworkExercise.setHomeworkId(homeworkExercises.get(0).getHomeworkId());
                return homeworkExercise;
            }).map(homeworkMapper::addHomeworkExercises).reduce(0, Integer::sum) > 0;
        }
        return false;
    }

    // 获取作业题目
    @Override
    public List<HomeworkExercises> getHomeworkExercises(Long homeworkId) {
        List<HomeworkExercises> homeworkExercises = homeworkMapper.getHomeworkExercises(homeworkId);
        if (homeworkExercises != null) return homeworkExercises.stream().map(homeworkExercise -> {
            homeworkExercise.setExerciseInfo(tExerciseService.getExercisesById(homeworkExercise.getExercisesId()));
            return homeworkExercise;
        }).collect(Collectors.toList());
        return null;
    }

    // 发布作业
    @Override
    public Boolean publishHomework(HomeworkPublish homeworkPublish) {
        if (homeworkPublish.getPublishId() == null || homeworkPublish.getPublishId() <= 0)
            return pushHomeworkPublish(homeworkPublish);
        else if (homeworkMapper.getHomeworkPublishById(homeworkPublish.getPublishId()) == null)
            return pushHomeworkPublish(homeworkPublish);
        else return updateHomework(homeworkPublish);
    }

    // 删除作业
    @Override
    public Boolean deleteHomework(Long homeworkId) {
        return homeworkMapper.deleteHomework(homeworkId) > 0;
    }

    // 取消发布作业
    @Override
    public Boolean cancelPublishHomework(Long publishId) {
        return homeworkMapper.cancelPublishHomework(publishId) > 0;
    }

    // 修改作业
    private Boolean updateHomework(THomework homework) {
        return homeworkMapper.updateHomework(homework) > 0;
    }

    // 添加作业
    private Boolean createHomework(THomework homework) {
        return homeworkMapper.createHomework(homework) > 0;
    }

    // 发布作业
    private Boolean pushHomeworkPublish(HomeworkPublish homeworkPublish) {
        return homeworkMapper.publishHomework(homeworkPublish) > 0;
    }

    // 修改发布作业
    private Boolean updateHomework(HomeworkPublish homeworkPublish) {
        return homeworkMapper.updatePublishHomework(homeworkPublish) > 0;
    }

    @Override
    public Boolean submitHomework(Long homeworkId, Long userId) {
        return null;
    }
}
